package xkp.lesson1;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 负责操作user_info表
 */
public class DBUserInfo {
    //操作数据库都要获取连接，获取连接很麻烦，能不能封装成一个方法
    public static List<UserInfo> selectAll() throws SQLException {
        List<UserInfo> userInfoList = new ArrayList<>();
        Connection connection = DBConnection.getConnection();
        String sql = "select * from user_info";
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet set = statement.executeQuery();
        while(set.next()){
             Integer userId = set.getInt("user_ID");
             String userName = set.getString("user_name");
             String userPwd = set.getString("user_pwd");
             String nickName  = set.getString("nick_name");
             String userSex = set.getString("user_sex");
             Integer userAge = set.getInt("user_age");
             String phoneNumber  = set.getString("phone_number");
             String email  = set.getString("email");
             UserInfo userInfo = new UserInfo(userId, userName, userPwd,
                     nickName, userSex, userAge, phoneNumber, email);
             userInfoList.add(userInfo);
        }
        set.close();
        statement.close();
        connection.close();
        return userInfoList;
    }


    public static UserInfo login(String userName,String userPwd) throws SQLException {
        UserInfo userInfo = null;
        Connection connection = DBConnection.getConnection();
        String sql = "select * from user_info where user_name = ? and user_PWD = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,userName);
        statement.setString(2,userPwd);

        ResultSet set = statement.executeQuery();
        while(set.next()){
            Integer userId = set.getInt("user_ID");
            String nickName  = set.getString("nick_name");
            String userSex = set.getString("user_sex");
            Integer userAge = set.getInt("user_age");
            String phoneNumber  = set.getString("phone_number");
            String email  = set.getString("email");
            userInfo = new UserInfo(userId, userName, userPwd,
                    nickName, userSex, userAge, phoneNumber, email);
            break;
        }
        set.close();
        statement.close();
        connection.close();
        return userInfo;
    }
}
